//
//  MainViewController.swift
//  weibo117
//
//  Created by 宋禹奇 on 15/6/23.
//  Copyright © 2015年 宋禹奇. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addChildViewControllers()
        
        //获取tabBar
        
        let tb = MainTabBar()
        
        setValue(tb, forKey: "tabBar")
        
        //加号按钮添加点击事件
        tb.compoesButton.addTarget(self, action: "compoesButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    func compoesButtonClick(){
        print(__FUNCTION__)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private func addChildViewControllers() {
        //获取json文件
        let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)!
        
        let data = NSData(contentsOfFile: path)!
        
        do{
            //解析json文件
            let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            for dict in array as! [[String: String]]{
            addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            
            }
        
        }catch{
        
        
        }
        
    }
    

    private func addChildViewController(vcName:String, title:String, imageName:String) {
        
        
        //获取info.plist 的信息
        let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        
        //将字符串转成类
        let cls:AnyClass = NSClassFromString(ns + "." + vcName)!
        
        
        //实例化控制器
        let vc = cls.alloc() as! UIViewController
        
        //设置
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
        
    }
}
